/**
 * @ngdoc controller
 * @name roles.index
 * @description
 */
(function () {
    'use strict';
    appModule.controller('file-index', ['$scope', '$uibModal', 'toastr', '$state', '$http', function ($scope, $uibModal, toastr, $state, $http) {
        console.log('首页')

        $scope.searchType = 0; //是否精确匹配

        //实现页面跳转并传递参数（查询关键字）
        $scope.searchText = "";
        $scope.search = function () {
            console.log($scope.searchType)
            if (!$scope.searchText) {
                $scope.searchText = "*"
            }
            $state.go('app.files-search', { paramsObj: { searchType: $scope.searchType, searchText: $scope.searchText } });

        }

        // 获取远程服务器的文件统计数据和文件标签数据
        $http({
            url: API_SERVICE_AMBAR+"api/search/stats?query=*", //发送请求的url路径  
        }).success(function (response) {
            console.log("文件统计数据和文件标签数据", response);
            $scope.extensions = response.extensions;
            console.log($scope.extensions);
            // 文件总数量
            $scope.allFilesCounts = response.extensions.total;
            // $scope.allFilesData = response.extensions.data;

            $scope.rangeFilterFilesArr = []; // 存放占比最大的前三位文件类型
            $scope.rangeFilterFilesArr = getMaxThree(response.extensions.data); //获取占比最大的前三位文件类型
            console.log($scope.rangeFilterFilesArr);
            // 文件标签总数
            $scope.tagsTotal = response.tags.total;
            // $scope.tagsDataArr = response.tags.data;
            $scope.filterTagsArr = []; //存放过滤掉的文件标签
            for (let i = 0; i < response.tags.data.length; i++) {
                // 过滤三种类型的标签
                if (response.tags.data[i].name != 'crawler-files' && response.tags.data[i].name != 'upload-files' && response.tags.data[i].name != 'ocr') {
                    $scope.filterTagsArr.push(response.tags.data[i]);
                }
            }
            $scope.rangeFilterTagsArr = []; // 存放占比最大的前三位标签
            $scope.rangeFilterTagsArr = getMaxThree($scope.filterTagsArr); //获取占比最大的前三位标签
            // console.log("占比最大的三个标签", $scope.rangeFilterTagsArr);
            // console.log("$scope.filterTagsArr", $scope.filterTagsArr);
        }).error(function (err) {
            toastr.error('获取服务器数据失败！');
        });

        // 得到最大的三个值
        function getMaxThree(arr) {
            var tempArr = []; //存放占比最大的前三位标签
            for (let i = 0; i < 3; i++) {
                var max = arr[0].hits_percent;
                for (let j = 0; j < arr.length; j++) {
                    if ((j + 1) < arr.length) { //防止数组越界
                        if (arr[j + 1].hits_percent >= max) {
                            max = arr[j + 1].hits_percent;
                        }
                    }
                }
                for (let k = 0; k < arr.length; k++) {
                    if (max == arr[k].hits_percent) {
                        tempArr.push(arr[k]);
                        arr.splice(k, 1); //删除指定下标的元素
                    }
                }
            }
            if(tempArr.length > 3){ //超过三个（即有多个并列的情况），则截取
                tempArr.splice(3);
            }
            return tempArr;
        }

        // 获取服务器的文件动态的统计数据
        $http({
            url: API_SERVICE_AMBAR+"api/stats", //发送请求的url路径  
        }).success(function (response) {
            console.log("stats",response);
            var uploadFilesOfToday = 0; //存放当天的上传文件数量
            var crawlerFilesOfToday = 0; //存放当天的爬虫文件数量
            var uploadFilesOfMonth = 0; //存放一个月的上传文件数量
            var crawlerFilesOfMonth = 0; //存放一个月的爬虫文件数量
            var uploadFilesOfWeek = 0; //存放一周的上传文件数量
            var crawlerFilesOfWeek = 0; //存放一周的爬虫文件数量
            // 获取当前时间戳
            $scope.timestamp = new Date().getTime();
            // 转换成所需要的日期格式
            $scope.currentDate = dateFormat($scope.timestamp);
            console.log("当前日期", $scope.currentDate);
            for (let i = response.procRate.data.length - 1; i >= 0; i--) {
                // 统计当天的文件数量
                if ($scope.currentDate == response.procRate.data[i].date) {
                    if(response.procRate.data[i]["upload-files"]){
                        uploadFilesOfToday = response.procRate.data[i]["upload-files"];
                    }
                    if(response.procRate.data[i]["crawler-files"]){
                        crawlerFilesOfToday = response.procRate.data[i]["crawler-files"];
                    }
                    $scope.filesCountsToday = uploadFilesOfToday + crawlerFilesOfToday;
                }

                if(response.procRate.data[i]["upload-files"]){
                    uploadFilesOfMonth += response.procRate.data[i]["upload-files"];
                }
                if(response.procRate.data[i]["crawler-files"]){
                    crawlerFilesOfMonth += response.procRate.data[i]["crawler-files"];
                }
            }
            // 统计近一个月的文件数量
            $scope.filesCountsMonth = uploadFilesOfMonth + crawlerFilesOfMonth;
            
            // 统计近一周的文件数量
            for (let j = response.procRate.data.length - 7; j < response.procRate.data.length; j++) {
                if(response.procRate.data[j]["upload-files"]){
                    uploadFilesOfWeek += response.procRate.data[j]["upload-files"];
                }
                if(response.procRate.data[j]["crawler-files"]){
                    crawlerFilesOfWeek += response.procRate.data[j]["crawler-files"];
                }
            }
            $scope.filesCountsWeek = uploadFilesOfWeek + crawlerFilesOfWeek;
        }).error(function (err) {
            toastr.error('获取服务器数据失败！');
        });

        // 转换日期格式
        function dateFormat(timestamp) {
            var time = new Date(timestamp);
            var year = time.getFullYear();
            var month = (time.getMonth() + 1) > 9 && (time.getMonth() + 1) || ('0' + (time.getMonth() + 1));
            var date = time.getDate() > 9 && time.getDate() || ('0' + time.getDate());
            // var hour = time.getHours() > 9 && time.getHours() || ('0' + time.getHours())
            // var minute = time.getMinutes() > 9 && time.getMinutes() || ('0' + time.getMinutes())
            // var second = time.getSeconds() > 9 && time.getSeconds() || ('0' + time.getSeconds())
            // var YmdHis = year + '/' + month + '/' + date + ' ' + hour + ':' + minute + ':' + second;
            var Ymd = year + '-' + month + '-' + date;
            return Ymd;
        }


    }

    ]);
    appModule.directive('renderFinish', function ($timeout) { //renderFinish监听ng-repeat是否渲染完
        return {
            restrict: 'A',
            link: function (scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function () {
                        //  console.log("sdgsag");
                        scope.$emit('ngRepeatFinished');
                    });
                }
            }
        };
    });

})();